﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MaxLeaf.Common;
using System.Data.SqlClient;
using MaxLeaf.DB;
using System.Data;


namespace MaxLeaf.DAL.K2K
{
    public class ImInvMasterDAL : BaseDAL
    {
        /// <summary>
        /// 物料
        /// </summary>
        public ImInvMasterDAL()
            : base()
        {
            strTableName = "t_IcItem";
            strUpdateFNumberTableName = "t_ICItemCore";
            strFieldNames = "FNumber,FShortNumber,FName,FFullName,FPOHighPrice,FPOHghPrcMnyType,FWWHghPrc,FWWHghPrcMnyType,FSOLowPrc,FSOLowPrcMnyType,FIsSale,FComCategoryID,FComTypeID,FSellMethod,FComBrandID,FModel,FPointsRate,FVIPPrice,FSilverVIPPrice,FGoldVIPPrice,FBusinessType,FErpClsID,FUnitGroupID,FUnitID,FOrderUnitID,FSaleUnitID,FProductUnitID,FStoreUnitID,FBarCodeUnitID,FKCCUnitID,FSecCoefficient,FQtyDecimal,FLowLimit,FHighLimit,FSecInv,FUseState,FIsEquipment,FIsSparePart,FIsCharSourceItem,FProfitRate,FISKFPeriod,FKFPeriod,FBatchManager,FBookPlan,FCheckCycUnit,FOIHighLimit,FOILowLimit,FSOHighLimit,FSOLowLimit,FInHighLimit,FInLowLimit,FPickHighLimit,FPickLowLimit,FTrack,FPlanPrice,FPriceDecimal,FAcctID,FSaleAcctID,FCostAcctID,FTaxRate,FCostProject,FIsSNManage,FCBRestore,FPlanTrategy,FPlanMode,FOrderTrategy,FFixLeadTime,FLeadTime,FTotalTQQ,FOrderInterVal,FQtyMin,FQtyMax,FBatchAppendQty,FOrderPoint,FBatFixEconomy,FBatChangeEconomy,FBatchSplitDays,FBatchSplit,FRequirePoint,FPlanPoint,FDefaultRoutingID,FDefaultWorkTypeID,FIsBackFlush,FPutInteger,FMRPCon,FMRPOrder,FCtrlType,FKanBanCapability,FIsKeyItem,FGrossWeight,FNetWeight,FMaund,FLength,FWidth,FHeight,FSize,FCubicMeasure,FStandardCost,FCBAppendRate,FStdBatchQty,FStandardManHour,FPieceRate,FInspectionLevel,FProChkMde,FWWChkMde,FSOChkMde,FWthDrwChkMde,FStkChkMde,FOtherChkMde,FSampStdCritical,FSampStdStrict,FSampStdSlight,FStkChkPrd,FStkChkAlrm,FInspectionProject,FExportRate,FImpostTaxRate,FConsumeTaxRate,FIsManage,FManageType,FLenDecimal,FCubageDecimal,FWeightDecimal,FAuxClassID,FSecUnitID,FDefaultLoc,FSPID,FOrderRector,FOrderPrice,FSalePrice,FIsSpecialTax,FStockTime,FBeforeExpire,FAPAcctID,FAdminAcctID,FGoodSpec,FProductPrincipal,FPlanner,FBackFlushStockID,FBackFlushSPID,FDailyConsume,FCBAppendProject,FCostBomID,FCBRouting,FStdPayRate,FChgFeeRate,FStdFixFeeRate,FOutMachFee,FOutMachFeeProject,FPOVAcctID,FPIVAcctID,FMCVAcctID,FPCVAcctID,FSLAcctID,FCAVAcctID,FIdentifier,FHSNumber,FFirstUnitRate,FSecondUnitRate,FCtrlStraregy,FDefaultReadyLoc,FSPIDReady,FPackTypeID,FOperator,FParentID";
            
            strFItemClassID = Const.FItemClassID_Item;
        }

        //因为有多个unit,保存unitid对应，不用每次从数据库取
        Dictionary<string, string> _dictUnit = null;

        public override int Update(DBAccess dbOrgK3Con, DBAccess dbDestK3Con, string strKeyValue)
        {
            KeyValuePair<string, IDataParameter[]> kvp = dbOrgK3Con.CreateCondParam(new Dictionary<string, object>() { { "FitemID", strKeyValue } });
            DataRow drOrg = dbOrgK3Con.GetDataFirstRow(string.Format("select fdetail from t_item where {0}", kvp.Key), kvp.Value);
            if (drOrg == null) throw new MaxLeafException(string.Format("t_item not exist FitemID {0}", strKeyValue));

            if (!CvtFunc.ToBoolean(drOrg["fdetail"]))
            {
                new MaxLeafException(string.Format("FitemID {0} fdetail {1}", strKeyValue, drOrg["fdetail"]));
            }
            return base.Update(dbOrgK3Con, dbDestK3Con, strKeyValue);
        }



        protected override void DAL_GetFieldData(DBAccess dbOrgK3Con, DBAccess dbDestK3Con, string strFieldName, DataRow drOrgData, DataRow drDestData)
        {
            if (strFieldName.Equals("FParentID", StringComparison.InvariantCultureIgnoreCase))
            {
                //根据fnumber得到上级组
                //物料上级组有4和2001两种
                string[] arrFnumber = CvtFunc.ToString(drOrgData["Fnumber"]).Split('.');
                if (arrFnumber.Length > 1)
                {
                    drDestData[strFieldName] =CvtFunc.ToString( new ImInvGroup_1DAL().GetDestMapKeyValue(dbOrgK3Con, dbDestK3Con, CvtFunc.ToString(drOrgData[strFieldName]))) ;

                    
                }
                else
                {
                    drDestData[strFieldName] = "0";
                };
            }
            else if (strFieldName.Equals("FitemID", StringComparison.InvariantCultureIgnoreCase))
            {
                if (CvtFunc.ToInt(drDestData[strFieldName]) != 0) return;
                string[] arrFnumber = CvtFunc.ToString(drOrgData["Fnumber"]).Split('.');
                string strFParentID = string.Empty;
                string strOrgFParentID = dbOrgK3Con.GetValue("select FitemID from t_item where FNumber=@FNumber and FItemClassID=" + strFItemClassID, new SqlParameter[] { new SqlParameter("@FNumber", string.Join(".", arrFnumber, 0, arrFnumber.Length - 1)) });
                if (arrFnumber.Length > 1)
                {
                    strFParentID = CvtFunc.ToString(new ImInvGroup_1DAL().GetDestMapKeyValue(dbOrgK3Con, dbDestK3Con, strOrgFParentID));
                }
                else
                {
                    strFParentID = "0";
                };

                //再FitemID
                drDestData[strFieldName] = GetFItemID(dbOrgK3Con, dbDestK3Con, strOrgFParentID, strFParentID, arrFnumber);


            }
            else if (strFieldName.Equals("FComTypeID", StringComparison.InvariantCultureIgnoreCase)
                || strFieldName.Equals("FSellMethod", StringComparison.InvariantCultureIgnoreCase)
                || strFieldName.Equals("FBusinessType", StringComparison.InvariantCultureIgnoreCase)
                || strFieldName.Equals("FUseState", StringComparison.InvariantCultureIgnoreCase)
                || strFieldName.Equals("FTrack", StringComparison.InvariantCultureIgnoreCase)
                || strFieldName.Equals("FPlanTrategy", StringComparison.InvariantCultureIgnoreCase)
                || strFieldName.Equals("FPlanMode", StringComparison.InvariantCultureIgnoreCase)
                || strFieldName.Equals("FOrderTrategy", StringComparison.InvariantCultureIgnoreCase)
                || strFieldName.Equals("FCtrlType", StringComparison.InvariantCultureIgnoreCase)
                ||strFieldName.Equals("FInspectionLevel", StringComparison.InvariantCultureIgnoreCase)
                || strFieldName.Equals("FProChkMde", StringComparison.InvariantCultureIgnoreCase)
                || strFieldName.Equals("FWWChkMde", StringComparison.InvariantCultureIgnoreCase)
                || strFieldName.Equals("FSOChkMde", StringComparison.InvariantCultureIgnoreCase)
                || strFieldName.Equals("FWthDrwChkMde", StringComparison.InvariantCultureIgnoreCase)
                || strFieldName.Equals("FStkChkMde", StringComparison.InvariantCultureIgnoreCase)
                || strFieldName.Equals("FOtherChkMde", StringComparison.InvariantCultureIgnoreCase)
                )
            {
                drDestData[strFieldName] = GetFTypeID(dbOrgK3Con, dbDestK3Con, CvtFunc.ToString(drOrgData[strFieldName]));
            }
            else if (strFieldName.Equals("FComCategoryID", StringComparison.InvariantCultureIgnoreCase))
            {
                drDestData[strFieldName] = new t_ComCategoryDAL().GetDestMapKeyValue(dbOrgK3Con, dbDestK3Con, CvtFunc.ToString(drOrgData[strFieldName]));
            }
            else if (strFieldName.Equals("FComBrandID", StringComparison.InvariantCultureIgnoreCase))
            {
                drDestData[strFieldName] = new t_ComBrandDAL().GetDestMapKeyValue(dbOrgK3Con, dbDestK3Con, CvtFunc.ToString(drOrgData[strFieldName]));
            }   
            else if (strFieldName.Equals("FUnitGroupID", StringComparison.InvariantCultureIgnoreCase))
            {

                //unit组，每组有一批单位
                string strFUnitGroupID = GetFUnitGroupID(dbOrgK3Con, dbDestK3Con, CvtFunc.ToString(drOrgData[strFieldName]));
                if (strFUnitGroupID.Length == 0)
                {
                    drDestData[strFieldName] = "0";
                }
                else
                {
                    drDestData[strFieldName] = strFUnitGroupID;
                    //默认单位
                    SetDefaulunitid(dbOrgK3Con, dbDestK3Con, CvtFunc.ToString(drOrgData[strFieldName]), strFUnitGroupID);
                }
            }
            else if (strFieldName.Equals("FUnitID", StringComparison.InvariantCultureIgnoreCase)
                ||strFieldName.Equals("FOrderUnitID", StringComparison.InvariantCultureIgnoreCase)
                || strFieldName.Equals("FSaleUnitID", StringComparison.InvariantCultureIgnoreCase)
                || strFieldName.Equals("FProductUnitID", StringComparison.InvariantCultureIgnoreCase)
                || strFieldName.Equals("FStoreUnitID", StringComparison.InvariantCultureIgnoreCase)
                || strFieldName.Equals("FBarCodeUnitID", StringComparison.InvariantCultureIgnoreCase)
                || strFieldName.Equals("FKCCUnitID", StringComparison.InvariantCultureIgnoreCase)
            )
            {
                //单位
                string strOrgFUnitID = CvtFunc.ToString(drOrgData[strFieldName]);
                string strFUnitID = string.Empty;
                if (_dictUnit != null && _dictUnit.ContainsKey(strOrgFUnitID))
                {
                    strFUnitID = _dictUnit[strOrgFUnitID];
                }
                else
                {
                    strFUnitID = GetFUnitID(dbOrgK3Con, dbDestK3Con, strOrgFUnitID, CvtFunc.ToString(drDestData["FUnitGroupID"]));
                }


                if (strFUnitID.Length == 0)
                {
                    drDestData[strFieldName] = "0";
                }
                else
                {
                    drDestData[strFieldName] = strFUnitID;
                }

                if (_dictUnit != null && !_dictUnit.ContainsKey(strOrgFUnitID))
                {
                    _dictUnit.Add(strOrgFUnitID, strFUnitID);
                }
            } 
            else if (strFieldName.Equals("FAcctID", StringComparison.InvariantCultureIgnoreCase)
                ||strFieldName.Equals("FSaleAcctID", StringComparison.InvariantCultureIgnoreCase)
                ||strFieldName.Equals("FCostAcctID", StringComparison.InvariantCultureIgnoreCase)
                )
            {
                drDestData[strFieldName] = GetAcctID(dbOrgK3Con, dbDestK3Con, CvtFunc.ToString(drOrgData[strFieldName]));
            }    
            else
            {
                base.DAL_GetFieldData(dbOrgK3Con, dbDestK3Con, strFieldName, drOrgData, drDestData);
            }
        }

        private string GetAcctID(DBAccess dbOrgK3Con, DBAccess dbDestK3Con, string strOrgAcctId)
        {
            if (strOrgAcctId.Length == 0 || strOrgAcctId.Equals("0"))
            {
                return "0";
            }
            t_AccountDAL dal = new t_AccountDAL();
            return dal.GetDestMapKeyValue(dbOrgK3Con, dbDestK3Con, strOrgAcctId);
        }

        private void SetDefaulunitid(DBAccess dbOrgK3Con, DBAccess dbDestK3Con, string strOrgFUnitGroupID, string strDestFUnitGroupID)
        {
            t_UnitGroupDAL dalGroup = new t_UnitGroupDAL();
            DataRow drOrgGroup = dalGroup.Gett_UnitGroup(dbOrgK3Con, strOrgFUnitGroupID);
            if (drOrgGroup == null)
            {
                return;
            }
            string strOrgFUnitID = CvtFunc.ToString(drOrgGroup["FDefaultUnitID"]);
            if (strOrgFUnitID.Equals("0"))
            {
                return;
            }


            string strFUnitID = string.Empty;
            if (_dictUnit != null && _dictUnit.ContainsKey(strOrgFUnitID))
            {
                strFUnitID = _dictUnit[strOrgFUnitID];
            }
            else
            {
                strFUnitID = GetFUnitID(dbOrgK3Con, dbDestK3Con, strOrgFUnitID, strDestFUnitGroupID);
            }


            if (strFUnitID.Length == 0)
            {

            }
            else
            {
                dalGroup.SetDefaulunitid(dbDestK3Con, strDestFUnitGroupID, strFUnitID);
            }

            if (_dictUnit != null && !_dictUnit.ContainsKey(strOrgFUnitID))
            {
                _dictUnit.Add(strOrgFUnitID, strFUnitID);
            }

        }

        private string GetFUnitID(DBAccess dbOrgK3Con, DBAccess dbDestK3Con, string strOrgFUnitID, string strFParentID)
        {
            t_MeasureUnitDAL dal = new t_MeasureUnitDAL();
            return dal.GetFMeasureUnitID(dbOrgK3Con, dbDestK3Con, strOrgFUnitID, strFParentID);
        }

        private string GetFUnitGroupID(DBAccess dbOrgK3Con, DBAccess dbDestK3Con, string strOrgFUnitGroupID)
        {
            t_UnitGroupDAL dal = new t_UnitGroupDAL();
            return dal.GetFUnitGroupID(dbOrgK3Con, dbDestK3Con, strOrgFUnitGroupID);

        }
        private string GetFTypeID(DBAccess dbOrgK3Con, DBAccess dbDestK3Con, string strOrgFInterID)
        {
            t_SubMessageDAL dal = new t_SubMessageDAL();
            return dal.GetFInterID(dbOrgK3Con, dbDestK3Con, strOrgFInterID);
        }

        private string GetFItemID(DBAccess dbOrgK3Con, DBAccess dbDestK3Con, string strOrgFParentID, string strFParentID, string[] arrFnumber)
        {

            const int intFDetail = 1;
            string strFItemId = string.Empty;
            t_ItemDAL dal = new t_ItemDAL(strFItemClassID, strUpdateFNumberTableName);


            strFItemId = dal.GetFItemId(dbOrgK3Con, dbDestK3Con, arrFnumber.Length, strOrgFParentID, strFParentID, string.Join(".", arrFnumber, 0, arrFnumber.Length), intFDetail);

            UpdateAccess(dbDestK3Con, strFItemId, strFParentID);


            return strFItemId;
        }



        private void UpdateAccess(DBAccess dbDestK3Con, string strFItemId, string strFParentID)
        {
            string strSql = @"
                if not exists(select * from access_t_IcItem where FitemID=@FitemID)
                begin
                 Insert into access_t_IcItem(FitemID,FParentIDX,FDataAccessView,FDataAccessEdit,FDataAccessDelete)
                 Values(@FitemID,@FParentIDX,convert(varbinary(7200),REPLICATE(char(255),100)),convert(varbinary(7200),REPLICATE(char(255),100)),convert(varbinary(7200),REPLICATE(char(255),100)))
                end
                ";
            dbDestK3Con.ExecuteSql(strSql, new SqlParameter[] { new SqlParameter("@FitemID", strFItemId), new SqlParameter("@FParentIDX", strFParentID) });
        }



        protected override DataTable DAL_GetData(DBAccess dbOrgK3Con, DBAccess dbDestK3Con, int intdataType, object objParam)
        {
            GetDataType dataType = (GetDataType)intdataType;

            if (dataType == GetDataType.OrgData)
            {
                return GetImInvMaster(dbOrgK3Con, CvtFunc.ToString(objParam));
            }


            return base.DAL_GetData(dbOrgK3Con, dbDestK3Con, intdataType, objParam);
        }



        private DataTable GetImInvMaster(DBAccess dbOrgK3Con, string strFItemID)
        {
            DataTable dtImInvMaster = null;
            if (dtImInvMaster == null)
            {
                dtImInvMaster = dbOrgK3Con.GetTableData("t_IcItem", new Dictionary<string, object> { { "FitemID", strFItemID } });

            }
            return dtImInvMaster;
        }

    }
}
